/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.gzx.plugin.ams.modular.commodity.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.fhs.trans.service.impl.DictionaryTransService;
import com.gzx.plugin.ams.modular.commodity.entity.AmsCommodityInfo;
import com.gzx.plugin.ams.modular.commodity.mapper.AmsCommodityInfoMapper;
import com.gzx.plugin.ams.modular.commodity.param.AmsCommodityInfoAddParam;
import com.gzx.plugin.ams.modular.commodity.param.AmsCommodityInfoEditParam;
import com.gzx.plugin.ams.modular.commodity.param.AmsCommodityInfoIdParam;
import com.gzx.plugin.ams.modular.commodity.param.AmsCommodityInfoPageParam;
import com.gzx.plugin.ams.modular.commodity.service.AmsCommodityInfoListService;
import com.gzx.plugin.ams.modular.commodity.service.AmsCommodityInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.tenant.TenantContext;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * ams_commodity_infoService接口实现类
 *
 * @author 刘志刚
 * @date 2024/12/27 13:41
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class AmsCommodityInfoServiceImpl extends ServiceImpl<AmsCommodityInfoMapper, AmsCommodityInfo> implements AmsCommodityInfoService, InitializingBean {

    public final AmsCommodityInfoMapper amsCommodityInfoMapper;

    private final DictionaryTransService dictionaryTransService;

    private final AmsCommodityInfoListService commodityInfoListService;

    @Override
    @DS("ams")
    public Page<AmsCommodityInfo> page(AmsCommodityInfoPageParam amsCommodityInfoPageParam) {
        QueryWrapper<AmsCommodityInfo> queryWrapper = new QueryWrapper<AmsCommodityInfo>().checkSqlInjection();
        if (ObjectUtil.isNotEmpty(amsCommodityInfoPageParam.getName())) {
            queryWrapper.lambda().like(AmsCommodityInfo::getName, amsCommodityInfoPageParam.getName());
        }
        if (ObjectUtil.isAllNotEmpty(amsCommodityInfoPageParam.getSortField(), amsCommodityInfoPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(amsCommodityInfoPageParam.getSortOrder());
            queryWrapper.orderBy(true, amsCommodityInfoPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(amsCommodityInfoPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(AmsCommodityInfo::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    @DS("ams")
    public void add(AmsCommodityInfoAddParam amsCommodityInfoAddParam) {
        AmsCommodityInfo amsCommodityInfo = BeanUtil.toBean(amsCommodityInfoAddParam, AmsCommodityInfo.class);
        amsCommodityInfoMapper.insert(amsCommodityInfo);
        refreshTransCache();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    @DS("ams")
    public void edit(AmsCommodityInfoEditParam amsCommodityInfoEditParam) {
        AmsCommodityInfo amsCommodityInfo = this.queryEntity(amsCommodityInfoEditParam.getId().toString());//
        BeanUtil.copyProperties(amsCommodityInfoEditParam, amsCommodityInfo);
        this.updateById(amsCommodityInfo);
        refreshTransCache();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    @DS("ams")
    public void delete(List<AmsCommodityInfoIdParam> amsCommodityInfoIdParamList) {
        // 执行删除
        String a = "1";
        amsCommodityInfoMapper.deleteBatchIds(CollStreamUtil.toList(amsCommodityInfoIdParamList, AmsCommodityInfoIdParam::getId));
        refreshTransCache();
    }

    @Override
    @DS("ams")
    public AmsCommodityInfo detail(AmsCommodityInfoIdParam amsCommodityInfoIdParam) {
        return this.queryEntity(amsCommodityInfoIdParam.getId().toString());//
    }

    @Override
    @DS("ams")
    public AmsCommodityInfo queryEntity(String id) {
        AmsCommodityInfo amsCommodityInfo = this.getById(id);
        if (ObjectUtil.isEmpty(amsCommodityInfo)) {
            throw new CommonException("ams_commodity_info不存在，id值为：{}", id);
        }
        return amsCommodityInfo;
    }

    /**
     * 获取所有的资产类别
     *
     * @return
     */
    @Override
    @DS("ams")
    public List<AmsCommodityInfo> listAll() {
        LambdaQueryWrapper<AmsCommodityInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(AmsCommodityInfo::getName, AmsCommodityInfo::getCode);
        return amsCommodityInfoMapper.selectList(wrapper);

    }

    /**
     * 根据资产编码获取资产名称
     *
     * @param code
     * @return
     */
    @Override
    public String getCommdityByCode(String code) {

        LambdaQueryWrapper<AmsCommodityInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(AmsCommodityInfo::getName);
        wrapper.eq(AmsCommodityInfo::getCode, code);
        List<AmsCommodityInfo> commodityInfos = amsCommodityInfoMapper.selectList(wrapper);

        if (commodityInfos.size() >= 0) {
            return commodityInfos.get(0).getName();
        }
        return "";
    }

    @Override
    public void afterPropertiesSet() {
        refreshTransCache();
    }

    private void refreshTransCache() {
        CompletableFuture.supplyAsync(() -> {
            // 使用redis能解决共享问题，但是性能没有直接取缓存的好。
            dictionaryTransService.makeUseRedis();
            try {
                TenantContext.disableTenantFilter();
                List<AmsCommodityInfo> projectList = commodityInfoListService.listAll();
                dictionaryTransService.refreshCache("commodity", projectList.stream().collect(Collectors.toMap(AmsCommodityInfo::getCode, AmsCommodityInfo::getName)));
            } finally {
                TenantContext.enableTenantFilter();
                TenantContext.clear();
            }
            return null;
        }).exceptionally(ex -> {
            ex.printStackTrace();
            log.error("异步任务发生异常:{}", ex.getMessage());
            return null;
        });
    }
}
